<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
    <style>
        .images-container {
            display: inline-block;
            /* overflow-x: auto; */
            /* 设置为auto或scroll */
            white-space: normal;
        }

        .image-box {
            position: relative;
            display: inline-block;
            margin-right: 1px;
            margin-bottom: 30px;
            /* 可根据需要调整 */
        }

        .text-overlay {
            position: absolute;
            top: -10px;
            left: 5%;
            /* width: 80%; */
            /* 文本元素宽度占比为80% */
            /* height: 80%; */
            /* 文本元素高度占比为80% */
            color: rgb(255, 0, 0);
            /* 文字颜色 */
            font-size: 20px;
            /* font-size: 2vw; */
            /* 字号 */
            font-weight: bold;
            /* 加粗 */
            /* padding: 10px; */
            /* padding: 1vw; */
            /* 内边距 */
            pointer-events: none;
            /* 避免文本层干扰图像操作事件 */
            z-index: 2;
            background-color: rgba(255, 255, 255, 0.5);
            /*设置白色半透明*/
            /* 层级高度设置为2，高于图像层的1 */
            /* opacity: 0.5; */
            /* 设置透明度为0.5 */
        }

        .image-box img {
            /* max-width: 100%; */
            /* max-width:  360px; */
            /* max-height:  1080px; */
            width: auto;
            /* height: 540px; */
            /* height: 1080px; */
            /* width: 360px; */
            margin: 3px;
            border: 3px solid rgb(0, 255, 64);
        }


        .controls {
            position: absolute;
            top: 100%;
            left: 0;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-around;
            background-color: rgba(41, 248, 0, 0.5);
            padding: 1px;
            box-sizing: border-box;
        }

        .controls button,
        .controls input[type=text] {
            max-width: calc(25% - 1px);
            /* 每个按钮宽度设置为四等份并减去间隔，保持平均分布 */
            flex-grow: 1;
            /* 当容器宽度变小时，元素宽度将自动调整以占用所有可用空间 */
            margin: 0 1px;
            /* 设置按钮间距 */
        }

        .controls input[type=text] {
            min-width: 40px;
            /* 可根据需要调整 */
            max-width: calc(50% - 10px);
            /* 这里将输入框的宽度设为剩余空间的一半，并留出左右 10px 的间隔 */
            margin-left: 8px;
            /* 可根据需要调整 */
        }
    </style>
</head>

<body>
    <fieldset>
        <legend>【投屏监听】 坐标:
            <input id="inputaaa" style="width: 100px;" /> 开启群控:
            <input id="qunKong" type="checkbox" />
        </legend>

        <!-- <ul> -->
        <!-- <li><img id="root_a90" src=""></li> -->
        <!-- </ul> -->


        <div class="images-container">

        </div>

    </fieldset>

    <script src="/lib/layui/layui.js" charset="utf-8"></script>
    <script>

        // let daiLi_userName = null
        // function chuanCan2(daiLi) {
        //     daiLi_userName = daiLi
        // }

        // setTimeout(function () {
        layui.use(['layer'], function () {

            let socketIds = parent.socketIds//改成map了
            let touPingDic = parent.touPingDic//投屏参数
            let yiPingKong = touPingDic.yiPingKong

            // touPingDic = {
            //     imgQuality: 50,//100图片质量
            //     imgScale: 0.5,//1图片缩放
            //     isOpenGray: false,//是否灰度化
            //     isOpenThreshold: false,//是否打开阈值
            //     imgThreshold: 60,//图像阈值
            //     reTime: 200//截图速度
            // }
            // console.log(socketIds);
            // console.log( Array.from(socketIds.keys()));
            var $ = layui.$
            var layer = layui.layer

            if (yiPingKong) {
                $("#qunKong").hide()
            }

            let socketId_keys = Array.from(socketIds.keys())//socketIds.keys()

            for (const [socketId, screenXY] of socketIds) {

                var $divv = `
                        <div class="image-box">
                            <img id="${socketId}" src="/images/1.jpg" draggable="false" style="height: ${touPingDic.touPingHeight}">
                            <div class="text-overlay">${socketId}</div>
                            <div class="controls">
                                <button id="back_${socketId}">返</button>
                                <button id="home_${socketId}">home</button>
                                <button id="recents_${socketId}">菜</button>
                                <input id="text_${socketId}" type="text">
                                <button id="input_${socketId}">输</button>
                            </div>
                        </div>`

                // $("ul").append($li);
                $(".images-container").append($divv);

                document.querySelector('#back_' + socketId).removeEventListener('click', btnClick.bind(null, socketId, "back"))
                document.querySelector('#back_' + socketId).addEventListener('click', btnClick.bind(null, socketId, "back"))

                document.querySelector('#home_' + socketId).removeEventListener('click', btnClick.bind(null, socketId, "home"))
                document.querySelector('#home_' + socketId).addEventListener('click', btnClick.bind(null, socketId, "home"))

                document.querySelector('#recents_' + socketId).removeEventListener('click', btnClick.bind(null, socketId, "recents"))
                document.querySelector('#recents_' + socketId).addEventListener('click', btnClick.bind(null, socketId, "recents"))

                document.querySelector('#input_' + socketId).removeEventListener('click', btnClick.bind(null, socketId, "input"))
                document.querySelector('#input_' + socketId).addEventListener('click', btnClick.bind(null, socketId, "input"))


                let devicePreviewBox = document.querySelector('#' + socketId + '');

                devicePreviewBox.removeEventListener('mousemove', (event) => {
                    deviceMouseMove(event, screenXY, socketId)
                });
                devicePreviewBox.addEventListener('mousemove', (event) => {
                    deviceMouseMove(event, screenXY, socketId)
                });

                devicePreviewBox.removeEventListener('mousedown', (event) => {
                    deviceMouseDown(event, screenXY, socketId)
                });
                devicePreviewBox.addEventListener('mousedown', (event) => {
                    deviceMouseDown(event, screenXY, socketId)
                }, true);

                devicePreviewBox.removeEventListener('mouseup', (event) => {
                    deviceMouseUp(event, screenXY, socketId)
                });
                devicePreviewBox.addEventListener('mouseup', (event) => {
                    deviceMouseUp(event, screenXY, socketId)
                }, true);
                // });

                if (yiPingKong) {
                    break
                }
            }


            function btnClick(socketId, action) {
                if (action != "input") {
                    // console.log(`${socketId}的${action}按钮被点击了！`);
                    if ($("#qunKong").prop("checked") || yiPingKong) {
                        ws.send(JSON.stringify({ type: "startAction", action: action + "()", wsid: socketId_keys }))
                    } else {
                        ws.send(JSON.stringify({ type: "startAction", action: action + "()", wsid: [socketId] }))
                    }
                } else {
                    let inputStr = document.querySelector('#text_' + socketId).value
                    document.querySelector('#text_' + socketId).value = ""
                    // console.log(`${socketId}的输入按钮被点击了！输入内容是:${inputStr}`);
                    if ($("#qunKong").prop("checked") || yiPingKong) {
                        ws.send(JSON.stringify({ type: "startAction", action: action + "('" + inputStr + "')", wsid: socketId_keys }))
                        // ws.send(JSON.stringify({ type: "startAction", action: "setText('" + inputStr + "')", wsid:socketId_keys }))
                    } else {
                        ws.send(JSON.stringify({ type: "startAction", action: action + "('" + inputStr + "')", wsid: [socketId] }))
                        // ws.send(JSON.stringify({ type: "startAction", action: "setText('" + inputStr + "')", wsid: [socketId] }))
                    }
                }
            }


            var lockReconnect = false;  //避免ws重复连接
            var ws = null;          // 判断当前浏览器是否支持WebSocket
            let api = readFile("/api/ip.txt")
            let userName = window.localStorage.getItem("userName")
            // console.log(userName);
            var wsUrl = "ws://" + api + "/wsRouter/" + userName + "/liuLanQi/liuLanQi/liuLanQi/liuLanQi/liuLanQi"
            createWebSocket(wsUrl);   //连接ws

            // 在全局定义一个字典对象
            let urlDict = {}


            // 监听窗口关闭事件，当窗口关闭时，
            window.onbeforeunload = function () {
                ws.close();
            }


            function createWebSocket(url) {
                try {
                    if ('WebSocket' in window) {
                        ws = new WebSocket(url);
                        // ws.binaryType = 'arraybuffer'; // 设置接受到的数据类型为 ArrayBuffer
                    }
                    initEventHandle();
                } catch (e) {
                    reconnect(url);
                    console.log(e);
                }
            }

            function initEventHandle() {
                ws.onclose = function () {
                    layer.msg("掉线重连中");
                    reconnect(wsUrl);
                };
                ws.onerror = function (e) {
                    alert("ws错误:" + e.name + e.number);
                };
                ws.onopen = function () {
                    layer.msg("连接服务器成功,投屏准备中...");
                    ws.send(JSON.stringify({
                        type: "touPing_start",
                        socketIds: yiPingKong ? [socketId_keys[0]] : socketId_keys,
                        touPingDic: touPingDic,
                        // daiLi_userName: daiLi_userName
                    }))
                };
                ws.onmessage = function (event) {
                    let dicData = JSON.parse(event.data)
                    if (dicData.type = "image/jpeg") {
                        let wsid = dicData.wsid
                        let image = document.getElementById(wsid);
                        if (!image) {
                            // console.log("没有image");
                            return
                        }
                        const blob = new Blob([new Uint8Array(dicData.binaryArr.data)], { type: 'image/jpeg' });

                        // 判断当前 URL 是否已经存在
                        if (urlDict[wsid]) {
                            URL.revokeObjectURL(urlDict[wsid]);
                        }
                        let url = URL.createObjectURL(blob);
                        urlDict[wsid] = url // 将URL对象保存到字典中
                        image.src = url;
                    } else {
                        layer.msg("@" + JOSN.stringify(dicData));
                    }
                };
            }

            function reconnect(url) {
                if (lockReconnect) return;
                lockReconnect = true;
                setTimeout(function () {     //没连接上会一直重连，设置延迟避免请求过多
                    createWebSocket(url);
                    lockReconnect = false;
                }, 9000);
            }

            function readFile(url) {
                var param;
                $.ajax({
                    url: url, //json文件位置
                    type: "GET", //请求方式为get
                    async: false,
                    dataType: "text", //返回数据格式为json
                    success: function (data) { //请求成功完成后要执行的方法 
                        param = data;
                    }
                })
                return param;
            }

            // 设备鼠标移动
            function deviceMouseMove(e, screenXY) {
                // console.log(e.srcElement);
                let box = e.srcElement//document.querySelector('.devicePreviewImg');
                // 竖屏
                if ("竖屏") {
                    // deviceMousePosition.x = Number(e.offsetX * (deviceInfo.screenWidth / box.width)).toFixed(0);
                    // deviceMousePosition.y = Number(e.offsetY * (deviceInfo.screenHeight / box.height)).toFixed(0);
                    // console.log(screenXY.device_width);
                    // console.log(screenXY.device_height);
                    $("#inputaaa").attr("value", "x:" + Number(e.offsetX * (screenXY.device_width / box.width)).toFixed(0) + " y:" + Number(e.offsetY * (screenXY.device_height / box.height)).toFixed(0))

                    // console.log("竖屏设备鼠标移动");
                } else {// "横屏") 
                    // deviceMousePosition.x = Number(e.offsetX * (deviceInfo.screenHeight / box.width)).toFixed(0);
                    // deviceMousePosition.y = Number(e.offsetY * (deviceInfo.screenWidth / box.height)).toFixed(0);

                    $("#inputaaa").attr("value", "x:" + Number(e.offsetX * (screenXY.device_height / box.width)).toFixed(0) + " y:" + Number(e.offsetY * (screenXY.device_width / box.height)).toFixed(0))

                    // console.log("横屏设备鼠标移动");
                    // console.log(deviceMousePosition.x, deviceMousePosition.y);
                }
            }


            // 设备鼠标按下
            function deviceMouseDown(e, screenXY) {
                // if (!deviceInfo.startPreview) {
                //     return
                // }
                let box = e.srcElement//document.querySelector('.devicePreviewImg');

                // 竖屏
                if ("竖屏") {

                    window.deviceMouseX1 = Number(e.offsetX * (screenXY.device_width / box.width)).toFixed(0);
                    window.deviceMouseY1 = Number(e.offsetY * (screenXY.device_height / box.height)).toFixed(0);

                    // console.log("竖屏设备鼠标移动");

                } else {// "横屏") 

                    window.deviceMouseX1 = Number(e.offsetX * (screenXY.device_height / box.width)).toFixed(0);
                    window.deviceMouseY1 = Number(e.offsetY * (screenXY.device_width / box.height)).toFixed(0);

                }

                // 按下记录开始鼠标位置

                window.deviceMouseStartTime = new Date().getTime();
                // console.log("设备鼠标按下", window.deviceMouseX1, window.deviceMouseY1,"图片高:",box.height);
            }

            // 设备鼠标松开
            function deviceMouseUp(e, screenXY, socketId) {

                let box = e.srcElement//document.querySelector('.devicePreviewImg');
                // 松开记录结束鼠标位置
                window.deviceMouseX2 = Number(e.offsetX * (screenXY.device_width / box.width)).toFixed(0)
                window.deviceMouseY2 = Number(e.offsetY * (screenXY.device_height / box.height)).toFixed(0)
                window.deviceMouseEndTime = new Date().getTime();
                let positionVal1 = window.deviceMouseX1 + "," + window.deviceMouseY1;
                let positionVal2 = window.deviceMouseX2 + "," + window.deviceMouseY2;
                // 坐标值不相同
                // console.log(positionVal1, positionVal2);
                if (positionVal1 !== positionVal2) {

                    let operateCode = 'swipe(' + window.deviceMouseX1 + ',' + window.deviceMouseY1 + ',' + window.deviceMouseX2 + ',' + window.deviceMouseY2 + ',' + (window.deviceMouseEndTime - window.deviceMouseStartTime) + ')';
                    // console.log("鼠标滑动", operateCode);
                    if ($("#qunKong").prop("checked") || yiPingKong) {
                        ws.send(JSON.stringify({ type: "startAction", action: operateCode, wsid: socketId_keys }))
                    } else {
                        ws.send(JSON.stringify({ type: "startAction", action: operateCode, wsid: [socketId] }))
                    }
                } else {
                    // 大于500毫秒 即为长按
                    if (window.deviceMouseEndTime - window.deviceMouseStartTime > 500) {
                        let operateCode = 'longClick(' + window.deviceMouseX1 + ',' + window.deviceMouseY1 + ')';
                        // console.log("鼠标长按", operateCode);


                        if ($("#qunKong").prop("checked") || yiPingKong) {
                            ws.send(JSON.stringify({ type: "startAction", action: operateCode, wsid: socketId_keys }))
                        } else {
                            ws.send(JSON.stringify({ type: "startAction", action: operateCode, wsid: [socketId] }))
                        }


                    } else {

                        let operateCode = 'click(' + window.deviceMouseX1 + ',' + window.deviceMouseY1 + ')';
                        // console.log("鼠标点击", operateCode, "屏幕:", screenXY,"图片高:",box.height);
                        if ($("#qunKong").prop("checked") || yiPingKong) {
                            ws.send(JSON.stringify({ type: "startAction", action: operateCode, wsid: socketId_keys }))
                        } else {
                            ws.send(JSON.stringify({ type: "startAction", action: operateCode, wsid: [socketId] }))
                        }

                    }
                }
            }

        });


        // }, 300)


    </script>
</body>

</html>